package com.example.demo.util;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
@Component
public class MinioUtil {
    @Autowired
    MinioClient minioClient;

    public void uploadFile(MultipartFile multipartFile, String bucket, String objectName) {
        PutObjectArgs putObjectArgs= null;
        try {
            String Name=multipartFile.getOriginalFilename();
            String[] split = Name.split("\\.");
            String suffix="."+split[1];
            putObjectArgs = PutObjectArgs.builder()
                    .object(objectName+suffix)
                    .bucket(bucket).stream(multipartFile.getInputStream(),multipartFile.getSize(),-1).build();
            minioClient.putObject(putObjectArgs);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void downloadFile(String fileName, String bucket, HttpServletResponse response) {

        try {
            GetObjectArgs getObjectArgs=GetObjectArgs.builder()
                    .object(fileName).bucket(bucket).build();
            InputStream in = minioClient.getObject(getObjectArgs);
            response.setHeader("Content-Disposition","attachment; fileName=" + fileName);
            IOUtils.copy(in,response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }




}
